from front.models import User


class FrontUserMiddleware(object):
    def __init__(self, get_response=None):
        print('1.初始化FrontUserMiddleware中间件...')
        self.get_response = get_response

    def __call__(self, request):
        print('2.request到达view前执行代码...')
        user_id = request.session.get('user_id')
        if user_id:
            try:
                user = User.objects.get(pk=user_id)
                request.frontuser = user
            except:
                request.frontuser = None
        else:
            request.frontuser = None
        response = self.get_response(request)
        print('3.response到达浏览器执行代码...')
        return response
